
#include "member_BAudioInput.h"
#include <BBuffer>

using namespace BWE;

member_BAudioInput::member_BAudioInput(BAudioInput* audioInput)
{
	boss = audioInput;
	format = Format_UChar;
	channelCount = 2;
	sampleRate = 22050;
	dirtyFormat = true;
#ifdef _WIN32
	hWaveIn = 0;
	for (int i = 0; i < 10; i++)
	{
		memset(wavhdr + i, 0, sizeof(WAVEHDR));
	}
	InitializeCriticalSection(&bufferSection);
#endif
}
member_BAudioInput::~member_BAudioInput()
{
#ifdef _WIN32
	DeleteCriticalSection(&bufferSection);
	for (int i = 0; i < 10; i++)
	{
		if (wavhdr[i].lpData)
			delete[] wavhdr[i].lpData;
	}
#endif
}

bool member_BAudioInput::initFormat()
{
	if (dirtyFormat)
	{
		fmtlen = 0;
		switch (format)
		{
		case Format_Char:
		case Format_UChar:
			fmtlen = 1;
			break;
		case Format_Short:
		case Format_UShort:
			fmtlen = 2;
			break;
		case Format_Int:
		case Format_UInt:
			fmtlen = 4;
			break;
		default:
			return false;
		}
#ifdef _WIN32
		wavform.wFormatTag = WAVE_FORMAT_PCM;
		wavform.nChannels = channelCount;
		wavform.nSamplesPerSec = sampleRate;
		wavform.nAvgBytesPerSec = sampleRate * channelCount * fmtlen;
		wavform.nBlockAlign = channelCount * fmtlen;
		wavform.wBitsPerSample = fmtlen * 8;
		wavform.cbSize = 0;
		for (int i = 0; i < 10; i++)
		{
			if (wavhdr[i].lpData)
				delete[] wavhdr[i].lpData;
			wavhdr[i].lpData = new char[wavform.nAvgBytesPerSec];
			wavhdr[i].dwBufferLength = wavform.nAvgBytesPerSec;
			wavhdr[i].dwBytesRecorded = 0;
			wavhdr[i].dwUser = 0;
			wavhdr[i].dwFlags = 0;
			wavhdr[i].dwLoops = 1;
			wavhdr[i].lpNext = 0;
			wavhdr[i].reserved = 0;
		}
#endif
		dirtyFormat = false;
	}
	return true;
}

void member_BAudioInput::emitSignals()
{
#ifdef _WIN32
	if (TRUE == TryEnterCriticalSection(&bufferSection))
	{
		if (buffer.size())
		{
			boss->emit(Signal_Input, buffer);
			buffer.reset();
		}
		LeaveCriticalSection(&bufferSection);
	}
#endif
#ifdef linux
	if (0 == pthread_mutex_lock(&mutex))
	{
		if (buffer.size())
		{
			boss->emit(Signal_Input, buffer);
			buffer.reset();
		}
		pthread_mutex_unlock(&mutex);
	}

#endif
}
